package com.wuliming.gulimall.product.service.impl;

import cn.hutool.core.util.StrUtil;
import com.wuliming.common.utils.R;
import com.wuliming.constant.ProductConstant;
import com.wuliming.gulimall.coupon.entity.SpuBoundsEntity;
import com.wuliming.gulimall.product.dao.AttrDao;
import com.wuliming.gulimall.product.dao.SpuInfoDao;
import com.wuliming.gulimall.product.entity.*;
import com.wuliming.gulimall.product.entity.vo.*;
import com.wuliming.gulimall.product.feign.CouponFeignService;
import com.wuliming.gulimall.product.feign.SearchFeignService;
import com.wuliming.gulimall.product.feign.WareFeignService;
import com.wuliming.gulimall.product.service.*;
import com.wuliming.to.SkuReductionTo;
import com.wuliming.to.es.SkuEsModel;
import com.wuliming.to.es.WareSkuStock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuliming.common.utils.PageUtils;
import com.wuliming.common.utils.Query;

import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
@Slf4j
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService imagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuInfo) {
        //保存基本商品信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.baseMapper.insert(spuInfoEntity);

        //保存描述图片信息
        List<String> decript = spuInfo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        //保存商品图片集信息
        List<String> images = spuInfo.getImages();
        imagesService.saveImages(spuInfoEntity.getId(), images);

        //保存规格参数
        List<BaseAttrs> baseAttrs = spuInfo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(baseAttr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setSpuId(spuInfoEntity.getId());
            valueEntity.setAttrId(baseAttr.getAttrId());
            AttrEntity attr = attrService.getById(baseAttr.getAttrId());
            valueEntity.setAttrName(attr.getAttrName());
            valueEntity.setAttrValue(baseAttr.getAttrValues());
            valueEntity.setQuickShow(baseAttr.getShowDesc());
            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);

        //保存积分信息
        Bounds bounds = spuInfo.getBounds();
        SpuBoundsEntity spuBoundsEntity = new SpuBoundsEntity();
        spuBoundsEntity.setSpuId(spuInfoEntity.getId());
        BeanUtils.copyProperties(bounds, spuBoundsEntity);
        couponFeignService.save(spuBoundsEntity);

        //保存当前spu对应的sku信息
        List<Skus> skus = spuInfo.getSkus();
        skus.stream().forEach(w -> {
            //保存sku的基本信息
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(w, skuInfoEntity);
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
            skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
            skuInfoEntity.setSaleCount(0L);
            List<Images> imagesList = w.getImages();
            imagesList.forEach(i -> {
                if (i.getDefaultImg() == 1) {
                    skuInfoEntity.setSkuDefaultImg(i.getImgUrl());
                }
            });
            skuInfoService.saveSkuInfo(skuInfoEntity);

            //保存sku的图片信息
            Long skuId = skuInfoEntity.getSkuId();
            List<SkuImagesEntity> skuImagesEntities = imagesList.stream().map(image -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setSkuId(skuId);
                skuImagesEntity.setImgUrl(image.getImgUrl());
                skuImagesEntity.setDefaultImg(image.getDefaultImg());
                skuImagesEntity.setImgSort(0);
                return skuImagesEntity;
            }).filter(item -> StrUtil.isNotEmpty(item.getImgUrl())).collect(Collectors.toList());
            skuImagesService.saveBatch(skuImagesEntities);

            //保存sku销售属性
            List<Attr> attrs = w.getAttr();
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuId);
                skuSaleAttrValueEntity.setAttrSort(0);
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

            //保存优惠，满减等信息
            SkuReductionTo skuReductionTo = new SkuReductionTo();
            BeanUtils.copyProperties(w, skuReductionTo);
            if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                skuReductionTo.setSkuId(skuId);
                couponFeignService.saveSkuReduction(skuReductionTo);
            }
        });
    }

    @Override
    public PageUtils queryPageCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (StrUtil.isNotEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }

        String catelogId = (String) params.get("catelogId");

        if (StrUtil.isNotEmpty(catelogId) && !"0".equals(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }

        String brandId = (String) params.get("brandId");

        if (StrUtil.isNotEmpty(brandId) && !"0".equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }

        String status = (String) params.get("status");
        if (StrUtil.isNotEmpty(status)) {
            wrapper.eq("publish_status", status);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        //查出所有spu对应的sku信息
        List<SkuInfoEntity> skus = skuInfoService.getSkuBySpuId(spuId);
        //查出当前spu对应的所有规格参数
        List<ProductAttrValueEntity> productAttrValueEntities = attrService.listforspu(spuId);
        List<Long> attrIds = productAttrValueEntities.stream().map(item ->
                item.getAttrId()
        ).collect(Collectors.toList());
        //远程调用库存服务查看是否有库存
        List<Long> longs = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> map = null;
        try {
            R r = wareFeignService.getSkuHasStock(longs);
            List<WareSkuStock> data = (List<WareSkuStock>) r.get("data");
            map = data.parallelStream().collect(Collectors.toMap(WareSkuStock::getSkuId, WareSkuStock::isHasStock));
        } catch (Exception e) {
            log.error("远程调用库存数量服务失败", e);
        }
        //查出可检索的规格参数id集合
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);
        HashSet<Long> set = new HashSet<>(searchAttrIds);
        //过滤出可以检索的规格参数并封装为es所需要的attr实体类
        List<SkuEsModel.Attr> attrList = attrIds.stream().filter(item -> set.contains(item)).map(item -> {
            SkuEsModel.Attr attr = new SkuEsModel.Attr();
            BeanUtils.copyProperties(item, attr);
            return attr;
        }).collect(Collectors.toList());
        //封装es需要的实体类
        Map<Long, Boolean> finalMap = map;
        List<SkuEsModel> skuEsModels = skus.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, skuEsModel);
            skuEsModel.setBrandImg(sku.getSkuDefaultImg());
            skuEsModel.setSkuPrice(sku.getPrice());
            //查询品牌和分类的名字信息
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            skuEsModel.setBrandId(brandEntity.getBrandId());
            //设置规格参数
            skuEsModel.setAttrs(attrList);
            //设置分类名称
            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            if (Objects.nonNull(finalMap)) {
                skuEsModel.setHasStock(finalMap.get("hasStock"));
            } else {
                skuEsModel.setHasStock(true);
            }
            //TODO 热度评分
            //skuEsModel.setHotScore(0L);

            return skuEsModel;
        }).collect(Collectors.toList());

        R r = searchFeignService.saveProduct(skuEsModels);

        if ((Integer) r.get("code") == 0) {
            SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
            spuInfoEntity.setId(spuId);
            spuInfoEntity.setPublishStatus(ProductConstant.AttrStatusEnum.UP.getCode());
            spuInfoEntity.setUpdateTime(new Date());
            updateById(spuInfoEntity);
        } else {
            //TODO 商品上传es失败重试
        }

    }

}